package com.zj.baseproxy.config.register;


import com.zj.baseproxy.annotation.BeanCreateRuleBeanName;
import com.zj.baseproxy.interfaces.BeanCreateRule;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AnnotatedElementUtils;

import java.util.Map;
import java.util.Optional;

/**
 * 生产bean对象
 *
 * @param <T>
 * @author arthur_zhou
 */
public class MapperFactoryBean<T> implements FactoryBean<T> {

    private final Class<T> mapperInterface;
    @Autowired
    private BeanCreateRule beanCreateRule;
    @Autowired
    private Map<String, BeanCreateRule> beanCreateRuleMap;

    MapperFactoryBean(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    @Override
    public T getObject() {
        Class<T> clazz = getObjectType();
        return Optional.ofNullable(clazz)
                .map(v -> AnnotatedElementUtils.getMergedAnnotation(v, BeanCreateRuleBeanName.class))
                .map(BeanCreateRuleBeanName::value)
                .map(v -> beanCreateRuleMap.getOrDefault(v, beanCreateRule))
                .map(v -> v.create(clazz))
                .orElse(null);
    }

    @Override
    public Class<T> getObjectType() {
        return this.mapperInterface;
    }

}

